package com.ybear.ybutils.utils

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.provider.Settings
import android.telephony.TelephonyManager
import java.nio.charset.StandardCharsets
import java.util.UUID

object UUIDUtils {
    private const val PREFS_FILE = "device_id.xml"
    private const val PREFS_DEVICE_ID = "device_id"

    /**
     * 获取设备ID
     * 需要 [Manifest.permission.READ_PRECISE_PHONE_STATE] 权限
     * @param context   上下文
     */
    @JvmStatic
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getDeviceId(context: Context): String {
        var uuid: UUID? = null
        synchronized(UUIDUtils::class.java) {
            val prefs = context.getSharedPreferences( PREFS_FILE, 0 )
            val id = prefs.getString( PREFS_DEVICE_ID, null )
            if ( id != null ) {
                uuid = UUID.fromString( id )
            } else {
                try {
                    val bs: ByteArray?
                    val androidId = Settings.Secure.getString(
                            context.contentResolver, Settings.Secure.ANDROID_ID
                    )
                    if( "9774d56d682e549c" != androidId ) {
                        bs = androidId.toByteArray( StandardCharsets.UTF_8 )
                        uuid = UUID.nameUUIDFromBytes( bs )
                    } else {
                        val deviceId = (context
                                .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).deviceId
                        bs = deviceId?.toByteArray( StandardCharsets.UTF_8 )
                        uuid = if ( bs != null ) UUID.nameUUIDFromBytes( bs ) else UUID.randomUUID()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                try {
                    prefs.edit().putString( PREFS_DEVICE_ID, uuid?.toString() ).apply()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return if (uuid == null) {
            ""
        } else {
            uuid.toString()
        }
    }

    @JvmStatic
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getPhoneIMEI(context: Context): String? {
        var ts: String? = ""
        try {
            ts = ( context.getSystemService( Service.TELEPHONY_SERVICE ) as TelephonyManager ).deviceId
        } catch (_: Exception) {
            //getDeviceId(int slotIndex) 在API 23及以上才能调用 所以这里用反射去执行
            //android 10以上已经获取不了imei了 用 android id代替
            try {
                ts = Settings.System.getString( context.contentResolver, Settings.Secure.ANDROID_ID )
            } catch (_: Exception) { }
        }
        return ts
    }
}